import React, {useState} from 'react';
import {Table, Input, Button, Popconfirm, Form, Typography, Space} from 'antd';

export default function Topic2_1() {
  const [form] = Form.useForm();
  const msgData = {
    "code": 0,
    "data": {
      "models": [
        {
          "id": 1,
          "sceneName": "场景01)",
          "comments": "要求：1.xxxxxxxxxxxxxxx; 2.xxxxxxxxxxxxxxx; 3.xxxxxxxxxxxxxxx; 4.xxxxxxxxxxxxxxx",
          "creator": "somebody",
          "modifier": "somebody",
          "createTime": "2020-03-11 11:05:35",
          "modifyTime": "2020-03-18 21:48:11",
          "url": "http://www.baidu.com",
          
        },
        {
          "id": 2,
          "sceneName": "场景02)",
          "comments": "要求：1.xxxxxxxxxxxxxxx; 2.xxxxxxxxxxxxxxx; 3.xxxxxxxxxxxxxxx; 4.xxxxxxxxxxxxxxx",
          "creator": "somebody",
          "modifier": null,
          "createTime": "2020-03-11 11:05:44",
          "url": "http://www.google.com",
          "modifyTime": "2020-03-11 11:05:44",
          
        },
      
      ],
      "total": 37
    },
    "message": "success"
  }
  const isEditing = (record) => record.id === editingKey;
  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.id);
      
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {...item, ...row});
        setData(newData);
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const deleteItem = (key) => {
    const newData = [...data];
    const index = newData.findIndex((item) => key === item.id);
    newData.splice(index, 1)
    setData(newData);
  }
  const cancel = () => {
    setEditingKey('');
  };
  
  const edit = (record) => {
    form.setFieldsValue({
      sceneName: '',
      comments: '',
      ...record,
    });
    setEditingKey(record.id);
  };
  
  const columns = [
    {
      title: '场景名称',
      dataIndex: 'sceneName',
      width: '10%',
      editable: true,
      render: (_, record) => {
        return (
          <Button target="_blank" href={record.url} type="link">{record.sceneName}</Button>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '15%',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <Space>
            <Button onClick={() => save(record.id)}
                    style={{
                      marginRight: 8,
                    }} type="link">保存</Button>
            <Popconfirm title="确认取消保存?" onConfirm={cancel}>
              <Button type="link">取消</Button>
            </Popconfirm>
          </Space>
        ) : (
          <Space>
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </Typography.Link>
            
            <Popconfirm title="确认取消保存?" onConfirm={() => deleteItem(record.id)}>
              <Typography.Link disabled={editingKey !== ''}>
                删除
              </Typography.Link>
            </Popconfirm>
          </Space>
        );
      },
    },
    {
      title: '设置角色',
      dataIndex: 'id',
      width: '10%',
      editable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '10%',
      editable: true,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      width: '10%',
      editable: true,
    },
    {
      title: '最后修改时间',
      dataIndex: 'modifyTime',
      width: '20%',
      editable: true,
    },
    {
      title: '修改人',
      dataIndex: 'modifyTime',
      width: '15%',
      editable: true,
    },
    {
      title: '描述',
      dataIndex: 'comments',
      width: '5%',
      editable: true,
    },
  
  ];
  const EditableCell = ({
                          editing,
                          dataIndex,
                          title,
                          inputType,
                          record,
                          index,
                          children,
                          ...restProps
                        }) => {
    return (
      <td key={index} {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            <Input/>
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  const setDataKey = () => {
    msgData.data.models.forEach((elm, index) => {
      elm.key = index
    })
  }
  setDataKey()
  const [data, setData] = useState(msgData.data.models);
  const [editingKey, setEditingKey] = useState('');
  
  
  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel,
        }}
      />
    </Form>
  )
}